package com.qd.system.service.org;

import com.cdqidi.exception.ApiException;
import com.qd.system.model.LoginUser;
import com.qd.system.model.Org;
import com.qd.system.model.OrgPerson;
import com.qd.system.model.Person;
import com.qd.system.service.login.LoginUserService;
import com.qd.system.service.person.PersonService;
import com.qd.system.treecl.TreeClDTO;
import com.qd.system.treecl.TreeClService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 机构信息操作
 *
 * @author sjk
 */
@Service
@RequiredArgsConstructor
public class OrgHoldService {

    private final OrgService orgService;
    private final PersonService personService;
    private final OrgPersonService orgPersonService;
    private final LoginUserService loginUserService;
    private final TreeClService treeClService;

    @Transactional(rollbackFor = Exception.class)
    public void deleteByOrgId(String orgId) {
        delete(orgId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteByOrgIds(List<String> ids) {
        ids.forEach(this::delete);
    }

    private void delete(String orgId) {
        final Org org = orgService.getById(orgId);
        if (null == org) {
            throw new ApiException("组织机构信息不存在");
        }
        if (Boolean.TRUE.equals(orgService.isExistsByParentId(orgId))) {
            throw new ApiException("存在下级组织，不能删除");
        }
        final List<Person> personList = personService.getListByOrgId(orgId);
        if (!personList.isEmpty()) {
            final List<String> list = personList.stream().map(Person::getPersonId).collect(Collectors.toList());
            personService.removeBatchIds(list);
            list.clear();
            personList.clear();
        }
        final List<OrgPerson> orgPersonList = orgPersonService.getListByOrgId(orgId);
        if (!orgPersonList.isEmpty()) {
            final List<String> list = orgPersonList.stream().map(OrgPerson::getOrgPersonId).collect(Collectors.toList());
            orgPersonService.removeBatchIds(list);
            list.clear();
            orgPersonList.clear();
        }
        final List<LoginUser> loginUserList = loginUserService.getListByOrgId(orgId);
        if (!loginUserList.isEmpty()) {
            final List<String> list = loginUserList.stream().map(LoginUser::getPersonId).collect(Collectors.toList());
            loginUserService.removeBatchIds(list);
            list.clear();
            loginUserList.clear();
        }
        orgService.removeById(orgId);
        final TreeClDTO treeClDto = orgService.buildTreeClDto().setParam(orgId);
        treeClService.delete(treeClDto);
        org.freeData();
        treeClDto.freeData();
    }
}